package com.goktech.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("index")
public class IndexController {
	
	@RequestMapping("")
	public ModelAndView index() {
		ModelAndView mav = new ModelAndView("index");
//		mav.setViewName("index");
		mav.addObject("username", "首页-username");
		
		return mav;
	}
	
	
	@RequestMapping("/01")
	public String index01(Model modelMap) {
		modelMap.addAttribute("username", "首页-modelMap");
		return "index";
		
	}
	
	/**
	 * 文件上传
	 * @param model
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 */
    @RequestMapping("/upload")
    public String uploadFile(Model model, @RequestParam("file1") MultipartFile file, HttpServletRequest request) throws IOException {

        System.out.println("开始");
        String path = request.getSession().getServletContext().getRealPath("res/upload");
        String fileName = file.getOriginalFilename();

        System.out.println(path);
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("fileUrl", request.getContextPath()+"res/upload/"+fileName);
        return "success";
    }
}
